/**
 * 公共请求方封装
 * 以uniapp为例子
 */
declare const uni:any; // 兼容uniapp防止ts报错

type CommonReponse = {
    code?: number;
    success?: boolean;
    data?: any;
    msg?: string;
}

type ReqConfig = {
    url: string;
    method?: 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT';
    header?: any;
    data?: any;
    config?: {
        loading?: boolean;
    };
    onSuccess?: (data: any) => any;
    onFail?: (err: Error) => any;
    onCompelete?: () => any;
}

// 默认请求配置
const getDefultReqConfig: ()=>ReqConfig = ()=>({
    url: '',
    method: 'POST',
    header: {
        // ... 默认请求头
    },
    data: {},
    config: {
        loading: false,     // 默认不需要loading加载款
    },
    onSuccess: (data: any) => data,
    onFail: (err: Error) => err,
    onCompelete: () => { },
})

// 过滤一般请求，这里用code=200代表后端请求正常
const commonResponseFilter = (resultData: CommonReponse) => {
    if (resultData.code == 200 || resultData.success == true) {
        return resultData.data;
    }
    // 登录异常
    if(resultData.code==401){
        // @to-do: 跳转登录页
        return false;
    }

    // @to-do: 打印异常信息
    throw new Error(resultData.msg);
}

const getHanledUrl = (url:string)=>{
	// #ifdef H5
		return '/server/'+url
	// #endif
	
	return 'http://192.168.22.36:5000' + String(url).trim()
}

export default async function request(reqConfig: ReqConfig): Promise<any> {
    const req = Object.assign({}, getDefultReqConfig(), reqConfig);
    if (!req.url) {
        return Promise.reject('请求的url不得为空');
    }

    if (req.config?.loading) {
        uni.showLoading({ title: '请求中...' });
    }

    // @to-do: 追加其他信息状态，如Cookie到header中
    req.header = Object.assign({ 
        //...
    }, req.header);

    return new Promise((resolve, reject) => {
        uni.request({
            url: getHanledUrl(reqConfig.url), //@to-do: 统一处理请求的url
            method: req.method,
            header: req.header, 
            data: req.data,
            success(res:any) {
                const data = commonResponseFilter(res.data as CommonReponse);
                resolve(req.onSuccess? req.onSuccess(data):data);
            },
            fail(err:any) {
                // @to-do: 打印异常日志
                const reasonError = new Error(`接口${req.url} 异常：`+ err.errMsg);
                reject(req.onFail? req.onFail(reasonError): reasonError);
            },
            complete() {
                req.config?.loading && uni.hideLoading();
                req.onCompelete&&req.onCompelete();
            },
        })
    });
}


